/**
 * 
 */
package com.seascape.swms.system.service;

import java.util.List;
import java.util.Map;

import org.beetl.sql.core.query.Query;
import org.springframework.stereotype.Service;

import com.google.common.collect.ImmutableMap;
import com.seascape.swms.framework.service.BaseService;
import com.seascape.swms.system.model.Role;
import com.seascape.swms.system.model.RoleResource;
import com.seascape.swms.system.model.UserRole;

/**
 * @author Lay
 *
 */
@Service
public class RoleService extends BaseService<Role>{

	public List<Role> queryRolesByUserId(Integer userId){
		Map<String,Object> params = ImmutableMap.<String,Object>builder().put("userId",userId).build();
		return sqlManager.select("userRole.queryRolesByUserId", Role.class, params);
	}
	
	public void assignUsers(Integer roleId,List<Integer> userIds) {
		Query<UserRole> query = sqlManager.query(UserRole.class).andEq("role_id", roleId);
		query.delete();
		for(Integer userId:userIds) {
			UserRole userRole = new UserRole();
			userRole.setUserId(userId);
			userRole.setRoleId(roleId);
			sqlManager.insert(userRole, true);
		}
	}
	
	public void assignResources(Integer roleId,List<Integer> resourceIds) {
		Query<RoleResource> query = sqlManager.query(RoleResource.class).andEq("role_id", roleId);
		query.delete();
		for(Integer resourceId:resourceIds) {
			RoleResource roleResource = new RoleResource();
			roleResource.setRoleId(roleId);
			roleResource.setResourceId(resourceId);
			sqlManager.insert(roleResource, true);
		}
	}
}
